import ip from "ip";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import Fastify from "fastify";
import vconf from "../utils/vconf.js";
import db from "../db/index.js";
import api from "../api/index.js";
const fastify = Fastify({ logger: true });
const config = vconf("config.yml");

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export default function () {
  //@Router
  fastify.register(import("fastify-routes"));
  fastify.register(import("fastify-autoload"), {
    dir: join(__dirname, "..", "routes"),
  });

  // 数据库链接
  db(fastify);
  api(fastify);

  //@Server
  const { server } = config;
  fastify.listen(server.port, server.host, (err) => {
    // console.log('fastify.routes=>>', fastify.routes) // Log all registered routes
    if (err) throw err;
    console.log(
      `api服务已启动: http://${ip.address()}:${fastify.server.address().port}/`
    );
  });
}
